#!/usr/bin/env groovy

@Library('pipeline-library') _

pipeline {
    agent {
        label 'ec2-jdk17'
    }

    triggers {
        cron('H 23 * * 1,2,3,4,5,7')
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 45)
    }

    environment {
        MAVEN_OPTS = '-Xms1024m -Xmx4096m -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3 -Dmaven.wagon.httpconnectionManager.ttlSeconds=125'
    }

    stages {
        stage ('Publish canary docker image') {
            steps {
                echo "Publishing docker image to dhis2/core-canary"
                script {
                    def branch="${env.GIT_BRANCH == 'master' ? 'latest' : env.GIT_BRANCH}"
                    def today = new Date()
                    def formatted = "${today.format('yyyyMMdd')}"
                    def source = "dhis2/core-dev:${branch}"
                    def target = "dhis2/core-canary:${branch}"
                    
                    sh "docker pull ${source}"
                    sh "docker tag ${source} ${target}"
                    sh "docker tag ${source} ${target}-${formatted}"
                    withDockerRegistry([credentialsId: "docker-hub-credentials", url: ""]) {
                        sh "docker push ${target}"
                        sh "docker push ${target}-${formatted}"
                    }           
                }
            }
        }

        stage ('Build') {
            steps {
                echo 'Building DHIS2 ...'
                script {
                    withMaven(options: [artifactsPublisher(disabled: true)]) {
                        sh 'mvn -X -T 4 --batch-mode --no-transfer-progress clean install -f dhis-2/pom.xml -P -default --update-snapshots -pl -dhis-test-coverage'
                    }
                }
            }
        }

        stage ('Sync WAR') {
            steps {
                echo 'Syncing WAR ...'
                sh 'curl "https://raw.githubusercontent.com/dhis2/dhis2-server-setup/master/ci/scripts/copy-war-s3.sh" -O'
                sh 'chmod +x copy-war-s3.sh'
                sh './copy-war-s3.sh canary ${GIT_BRANCH}'
            }
        }

        stage ('Delete old WARs') {
            steps {
                echo 'Deleting old WARs ...'
                sh 'curl "https://raw.githubusercontent.com/dhis2/dhis2-server-setup/master/ci/scripts/delete-old-wars.sh" -O'
                sh 'chmod +x delete-old-wars.sh'
                sh './delete-old-wars.sh ${GIT_BRANCH}'
            }
        }

        stage('Update IM Play instance') {
            environment {
                HTTP = "http --check-status"
                IM_REPO_URL = "https://github.com/dhis2-sre/im-manager"
                IM_HOST = "https://api.im.dhis2.org"
                INSTANCE_URL = "https://play.im.dhis2.org/nightly"
                IMAGE_REPOSITORY = "core-canary"
                IMAGE_PULL_POLICY = "Always"
                FLYWAY_MIGRATE_OUT_OF_ORDER = "true"
                FLYWAY_REPAIR_BEFORE_MIGRATION = "true"
                INSTANCE_TTL = "315360000"
                STARTUP_PROBE_FAILURE_THRESHOLD = "50"
                LIVENESS_PROBE_TIMEOUT_SECONDS = "3"
                READINESS_PROBE_TIMEOUT_SECONDS = "3"
            }

            steps {
                script {
                    withCredentials([usernamePassword(credentialsId: 'dhis2-im-bot', passwordVariable: 'PASSWORD', usernameVariable: 'USER_EMAIL')]) {
                        dir('im-manager') {
                            gitHelper.sparseCheckout(IM_REPO_URL, "${gitHelper.getLatestTag(IM_REPO_URL)}", '/scripts')

                            echo 'Creating DHIS2 instance on IM...'
                            def branch = ""
                            if (env.GIT_BRANCH == 'master') {
                                env.IMAGE_TAG = "latest"
                                env.DATABASE_ID = "test-dbs-sierra-leone-dev-sql-gz"
                            } else {
                                env.IMAGE_TAG = env.GIT_BRANCH
                                branch = "-${env.GIT_BRANCH.replace(".", "-")}"

                                dir('scripts/databases') {
                                    env.DATABASE_ID = sh(
                                            returnStdout: true,
                                            script: "./list.sh | jq -r '.[] | select(.name == \"test-dbs\") | .databases[] | select(.name == \"sierra-leone/${env.GIT_BRANCH}.sql.gz\") | .slug'"
                                    ).trim()
                                }
                            }

                            sh '[ -n "$DATABASE_ID" ]'
                            echo "Database: ${env.DATABASE_ID}"

                            dir('scripts/instances') {
                                description = "DHIS 2 nightly development branch ${env.GIT_BRANCH}"
                                sh "./findByName.sh play nightly${branch} | jq --exit-status 'has(\"id\")' && ./restart.sh \$(./findByName.sh play nightly${branch} | jq '.instances[] | select(.stackName==\"dhis2-core\") | .id') || ./deploy-dhis2.sh play nightly${branch} ${description}"
                                timeout(10) {
                                    waitFor.statusOk("${env.INSTANCE_URL}${branch}")
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    post {
        failure {
            script {
                slack.sendMessage(
                    '#ff0000',
                    slack.buildUrl() + "\nLatest run on ${GIT_BRANCH} failed and needs investigation. :detective-duck:\nCommit: <${GIT_URL}/commit/${GIT_COMMIT}|${GIT_COMMIT}>",
                    'team-backend'
                )
            }
        }

        aborted {
            script {
                slack.sendTimedoutMessage()
            }
        }
    }
}
